import argparse
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, RichLog, Input
from textual.containers import VerticalScroll
from textual.reactive import var

from src.core.dsl_interpreter import DSLInterpreter
from src.scripts.example_scripts import get_script_by_name

class ChatApp(App):
    """A Textual chat application for the DSL bot."""

    BINDINGS = [
        ("ctrl+c", "quit", "Quit"),
        ("ctrl+d", "toggle_dark", "Toggle Dark Mode"),
    ]

    def __init__(self, script_name: str, user_name: str):
        super().__init__()
        self.script_name = script_name
        self.user_name = user_name
        self.interpreter = DSLInterpreter()

    def compose(self) -> ComposeResult:
        """Create child widgets for the app."""
        yield Header(name="DSL Chatbot")
        yield VerticalScroll(
            RichLog(id="chat_log", highlight=True),
            id="log-container"
        )
        yield Input(placeholder="Enter your message...", id="chat_input")
        yield Footer()

    def on_mount(self) -> None:
        """Called when the app is mounted."""
        log = self.query_one(RichLog)
        log.write("[bold green]Welcome to the DSL Chatbot![/bold green]")
        log.write(f"👤 User: [yellow]{self.user_name}[/yellow]")
        
        script_text = get_script_by_name(self.script_name)
        if self.interpreter.load_script(script_text):
            log.write(f"✅ Script '[cyan]{self.script_name}[/cyan]' loaded successfully.")
        else:
            log.write(f"❌ [bold red]Error:[/bold red] Failed to load script '[cyan]{self.script_name}[/cyan]'.")
        
        self.query_one(Input).focus()

    async def on_input_submitted(self, message: Input.Submitted) -> None:
        """Handle user input submission."""
        prompt = message.value
        if not prompt:
            return

        log = self.query_one(RichLog)
        log.write(f"👤 [yellow]You:[/yellow] {prompt}")
        
        # Process input and get reply
        # For more complex operations, consider running this in a worker thread
        reply = self.interpreter.process_user_input(self.user_name, prompt)
        log.write(f"🤖 [bold blue]Bot:[/bold blue] {reply}")
        
        self.query_one(Input).value = ""

def main():
    """Parse arguments and run the TUI application."""
    parser = argparse.ArgumentParser(description='DSL 智能客服 TUI')
    parser.add_argument(
        '--script',
        type=str,
        default='combined',
        help="要加载的脚本名称 (例如 'combined' 或 'simple')"
    )
    parser.add_argument(
        '--user',
        type=str,
        default='fusihan1',
        help='用于对话的用户名'
    )
    args = parser.parse_args()

    app = ChatApp(script_name=args.script, user_name=args.user)
    app.run()

if __name__ == '__main__':
    main()
